<?php

namespace Modules\Api\Service;

use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\AddressRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Service\PublicService;

class MallOrderService
{
    /**
     * 获取用户默认收货地址
     * @param $user_id
     * @return array
     */
    public function get_user_address($user_id)
    {
        //获取用户收货地址
        $arr_option['where'] = ['user_id' => $user_id];
        $arr_option['field'] = ['id', 'username', 'user_id', 'phone', 'province', 'city', 'area', 'address', 'is_defaule'];
        $address = AddressRepository::get_all($arr_option)->toArray();
        $address_info = [];
        if ($address) {
            foreach ($address as $key => $value) {
                if ($value['is_defaule'] == 1) {
                    $address_info = [
                        'address_id' => $value['id'], 'username' => $value['username'], 'phone' => $value['phone'],
                        'address' => $value['province'] . $value['city'] . $value['area'] . $value['address'],
                    ];
                    break;
                } else {
                    $address_info = [
                        'address_id' => $value['id'], 'username' => $value['username'], 'phone' => $value['phone'],
                        'address' => $value['province'] . $value['city'] . $value['area'] . $value['address'],
                    ];
                }
            }
        }

        return $address_info;
    }

    /**
     * 结算台--预生成积分订单
     * @param array $data
     * @param bool $type
     * @return array
     */
    public function pre_build_order(array $data, $type = true)
    {
        try {
            if (empty($data['shop_id'])) {
                return hello_error('门店id不能为空');
            }
            if (empty($data['goods_id'])) {
                return hello_error('商品id不能为空');
            }
            if (empty($data['product_id'])) {
                return hello_error('产品id不能为空');
            }
            if (empty($data['goods_num'])) {
                return hello_error('商品数量不能为空');
            }

            $g_field['field'] = ['id', 'name', 'price'];
            $goods_obj = GoodsRepository::get_one((int)$data['goods_id'], $g_field);

            $p_field['field'] = ['id', 'goods_id', 'goods_specs_id', 'integral', 'stock', 'pic'];
            $p_field['with'] = ['specs'];
            $product_obj = GoodsProductRepository::get_one((int)$data['product_id'], $p_field);

            if ($goods_obj->first() && $product_obj->first()) {

                $goods = $goods_obj->toArray();
                $product = $product_obj->toArray();

                if ($type) {
                    $address = self::get_user_address($data['user_id']);//小程序
                } else {
                    $address = AddressService::get_defaule_address()['data'];//APP
                }

                $total_integral = (int)$data['goods_num'] * $product['integral'];
                $info = [
                    'shop_id' => $data['shop_id'],
                    'goods_id' => $goods['id'],
                    'goods_name' => $goods['name'],
                    'goods_pic' => $product['pic']['full_src'],
                    'goods_specs' => $product['specs']['name'],
                    'goods_price' => $goods['price'],
                    'goods_integral' => $product['integral'],
                    'product_id' => $product['id'],
                    'goods_num' => $data['goods_num'],
                    'total_integral' => $total_integral,
                    'address' => $address ? $address : null
                ];

                return hello_success('成功', $info);
            }

            return hello_error('商品不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 订单数据验证
     * @param $arrInput
     * @return array
     */
    public function check_arr_input($arrInput)
    {
        if (empty($arrInput['shop_id'])) {
            return ['state' => 1, 'msg' => '门店id不能为空'];
        }
        if (empty($arrInput['user_address_id'])) {
            return ['state' => 1, 'msg' => '请添加收货地址'];
        }

        if (empty($arrInput['goods_id'])) {
            return ['state' => 1, 'msg' => '商品id不能有空'];
        }
        if (empty($arrInput['goods_num'])) {
            return ['state' => 1, 'msg' => '产品数量不能有空'];
        }
        if (empty($arrInput['goods_product_id'])) {
            return ['state' => 1, 'msg' => '产品id不能有空'];
        } else {
            $product = GoodsProductRepository::get_one($arrInput['goods_product_id']);
            $num = intval($arrInput['goods_num']);
            if ($product->first()) {
                if ($num > $product->stock) {
                    return ['state' => 1, 'msg' => '库存不足'];
                }
                $arrInput['goods_integral'] = $product->integral;  //单个商品积分
                $arrInput['order_integral'] = $product->integral * $num;  //订单总积分
            } else {
                return ['state' => 1, 'msg' => '数据有误'];
            }

            $arr_option['field'] = ['id', 'integral'];
            $user = UsersRepository::get_one((int)$arrInput['user_id'], $arr_option);

            if ($arrInput['order_integral'] > $user->integral) {
                return ['state' => 1, 'msg' => '积分不足，订单创建失败'];
            }
        }

        return $arrInput;
    }

    /**
     * 生成积分订单
     * @param array $arr_input
     * @return array
     */
    public function create_mall_order(array $arr_input)
    {
        try {
            //对提交的数据进行验证
            $data = self::check_arr_input($arr_input);
            if ($data['state'] == 1) {
                return hello_error($data['msg']);
            }
            $product_id = intval($data['goods_product_id']);
            $goods_num = intval($data['goods_num']);

            $order_data = [
                'order_no' => random_order_sn('GO'),
                'shop_id' => intval($data['shop_id']),
                'user_id' => intval($data['user_id']),
                'goods_id' => intval($data['goods_id']),
                'goods_product_id' => $product_id,
                'goods_num' => $goods_num,
                'goods_integral' => $data['goods_integral'],
                'order_integral' => $data['order_integral'],
                'user_address_id' => intval($data['user_address_id']),
                'remark' => $data['remark']
            ];

            //生成订单数据
            $order = OrderMallRepository::add_one($order_data);

            $res = [
                'order_id' => $order->id,
                'order_no' => $order->order_no,
                'order_integral' => $order->order_integral
            ];

            //扣除库存
            GoodsProductRepository::decrease_num($product_id, 'stock', $goods_num);

            return hello_success('订单创建成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 支付订单
     * @param array $data
     * @return array
     */
    public function pay_mall_order(array $data)
    {
        try {

            if (empty($data['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($data['order_no'])) {
                return hello_error('订单编号不能为空');
            }

            //获取订单信息
            $map = ['id' => $data['order_id'], 'order_no' => $data['order_no'], 'user_id' => $data['user_id'], 'pay_status' => 1, 'status' => 1];
            $arr_option['with'] = ['getGoodsInfo'];
            $order_obj = OrderMallRepository::get_one_by_where($map , $arr_option  );
            //获取用户的积分信息


            if ($order_obj->first()) {
                //修改订单状态
                $upArray = ['pay_status' => 2, 'pay_time' => date('Y-m-d H:i:s', time())];
                $rew = OrderMallRepository::edit_one($map, $upArray);

                //修改商品售出的数量
                GoodsRepository::increase_num($order_obj->goods_id, $order_obj->goods_num);
                GoodsProductRepository::increase_num($order_obj->goods_product_id, 'sell', $order_obj->goods_num);


                //添加用户积分变更记录
                $arrInput = [
                    'type' => 2,
                    'user_id' => $data['user_id'],
                    'order_id' => $order_obj->id,
                    'order_type' => 1,
                    'total_fee' => $order_obj->order_integral,
                    'remarks' => '积分兑换商品'
                ];

                //获取用户的积分信息
                $user_info = UsersRepository::get_one( (int) $data['user_id'] , (array) ['field'=>['id','integral','integral_all','status']]);
                if( empty( $user_info->first() ) ){
                    return ['state'=> 1,'msg'=>'获取用户信息失败','data'=>[],'error'=>''];
                }
                $user_info = $user_info->toarray();

                $integral = PublicService::user_integral_change((array)$arrInput , (array) $user_info );
                if ($integral['state'] == 1) {
                    return $integral;
                }
                $shop_name = $order_obj->getGoodsInfo->name;
                if( mb_strlen( $order_obj->getGoodsInfo->name) > 20 ){
                    $shop_name = mb_substr( $order_obj->getGoodsInfo->name , 0 , 20 );
                }
                $integral = $user_info['integral'] - $order_obj->order_integral;
                $content = '您刚兑换了【'.$shop_name.'...】,消费了'.$order_obj->order_integral.'积分,最新积分余额：'. $integral;
                $message_extras = [
                    'sys_type' => 1,    //1:积分消息类型   2：检测消息类型
                ];

                add_message('','系统消息',$content,$data['user_id'],1,$order_obj->id,[],$message_extras);
                return hello_success('ok');
            }
            return hello_error('该订单不存在或无效，请重新下单');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取用户订单列表
     * @param array $arr_input
     * @return array
     */
    public function get_mall_order_list(array $arr_input)
    {
        try {
            $arr_where['user_id'] = $arr_input['user_id'];
            $status = (int)$arr_input['status'];
            if (!empty($status)) {
                if ($status == 1) { //待支付
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 1;
                } elseif ($status == 2) {//待发货
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 2;
                } elseif ($status == 3) {//待收货
                    $arr_where['status'] = 2;
                } elseif ($status == 4) {//待评价
                    $arr_where['status'] = 3;
                }
            }

            $arr_option['with'] = ['getGoodsInfo', 'product_info', 'shop_name'];
            $arr_option['field'] = ['id', 'order_no', 'shop_id', 'goods_num', 'goods_id', 'goods_product_id', 'goods_integral', 'order_integral', 'status', 'pay_status', 'created_at'];
            $arr_list = OrderMallRepository::get_list_by_where($arr_where, $arr_option);
            $list = list_page_data($arr_list);

            $order['list'] = [];
            foreach ($list['data'] as $key => $value) {
                $order['list'][] = [
                    'id' => $value['id'],
                    'order_no' => $value['order_no'],
                    'shop_id' => $value['shop_id'],
                    'shop_name' => $value['shop_name']['name'],
                    'goods_num' => $value['goods_num'],
                    'goods_integral' => $value['goods_integral'],
                    'order_integral' => $value['order_integral'],
                    'goods_name' => $value['get_goods_info']['name'],
                    'goods_pic' => $value['product_info']['pic']['full_src'],
                    'goods_specs' => $value['product_info']['specs']['name'],
                    'status' => $value['status'],
                    'pay_status' => $value['pay_status'],
                    'order_status' => OrderMallRepository::order_status($value['status'], $value['pay_status']),
                    'created_at' => $value['created_at'],
                ];
            }

            $order['page'] = $list['page_data'];

            return hello_success('获取成功！', $order);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取订单详情
     * @param array $arr_input
     * @return array
     */
    public function get_mall_order_info(array $arr_input)
    {
        try {
            $order_id = (int)$arr_input['order_id'];
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            //获取订单详情
            $arr_option['with'] = ['getGoodsInfo', 'getAddressInfo', 'product_info', 'getExpressInfo', 'shop_name'];
            $order_obj = OrderMallRepository::get_one($order_id, (array)$arr_option);
            if ($order_obj->first()) {
                $order = $order_obj->toArray();

                $detail['order'] = [
                    'id' => $order['id'],
                    'order_no' => $order['order_no'],
                    'shop_id' => $order['shop_id'],
                    'shop_name' => $order['shop_name']['name'],
                    'shop_phone' => $order['shop_name']['phone'],
                    'order_integral' => $order['order_integral'],
                    'status' => $order['status'],
                    'pay_status' => $order['pay_status'],
                    'pay_type' => '积分兑换',
                    'pay_time' => $order['pay_time'],
                    'order_status' => OrderMallRepository::order_status($order['status'], $order['pay_status']),
                    'remark' => $order['remark'],
                    'created_at' => $order['created_at'],
                    'express' => $order['get_express_info']['name'],
                    'delivery_no' => $order['delivery_no'],
                    'delivery_price' => '包邮',
                    'delivery_time' => $order['delivery_time'],
                    'receiving_time' => $order['receiving_time'],
                ];
                $detail['goods'] = [
                    'goods_id' => $order['goods_id'],
                    'goods_num' => $order['goods_num'],
                    'goods_integral' => $order['goods_integral'],
                    'goods_name' => $order['get_goods_info']['name'],
                    'goods_pic' => $order['product_info']['pic']['full_src'],
                    'goods_specs' => $order['product_info']['specs']['name'],
                ];
                $address = $order['get_address_info'];
                $detail['address'] = [
                    'username' => $address['username'],
                    'phone' => $address['phone'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address']
                ];

                return hello_success('获取成功！', $detail);
            }

            return hello_error('该订单不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 确认收货
     * @param array $arr_input
     * @return array
     */
    public function mall_order_take_over(array $arr_input)
    {
        try {
            $order_id = intval($arr_input['order_id']);
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            $map = ['id' => $order_id, 'user_id' => $arr_input['user_id']];
            $upArray = ['status' => 3, 'receiving_time' => date('Y-m-d H:i:s', time())];
            if (OrderMallRepository::edit_one($map, $upArray)) {
                return hello_success('收货成功！');
            }

            return hello_error('数据有误');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 取消订单
     * @param array $arr_input
     * @return array
     */
    public function cancel_mall_order(array $arr_input)
    {
        try {
            $order_id = intval($arr_input['order_id']);
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            $map = ['id' => $order_id, 'user_id' => $arr_input['user_id']];
            $upArray = ['status' => 5];
            if (OrderMallRepository::edit_one($map, $upArray)) {
                return hello_success('取消成功！');
            }

            return hello_error('数据有误');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除订单
     * @param array $arr_input
     * @return array
     */
    public function del_mall_order(array $arr_input)
    {
        try {
            $order_id = intval($arr_input['order_id']);
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            $map = ['id' => $order_id, 'user_id' => $arr_input['user_id']];
            if (OrderMallRepository::delete_by_where($map)) {
                return hello_success('删除成功！');
            }

            return hello_error('数据有误');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }
}